package net.yondervision.hrfsp.sdk.esign.core.util;

import cn.hutool.json.JSONUtil;
import lombok.experimental.UtilityClass;
import net.yondervision.hrfsp.sdk.esign.domain.AbstractESignResponse;
import net.yondervision.hrfsp.sdk.esign.domain.DefaultESignResponse;
import net.yondervision.hrfsp.sdk.esign.domain.ESignRequest;

/**
 * @author Cash Zhang
 * @version v1.0
 * @since 2019/09/27 17:08
 */
@UtilityClass
public class DefaultResultJsonResolver {

  public <T extends AbstractESignResponse> T resolve(ESignRequest<T> request, String resultJson) {

    if (!JSONUtil.isJson(resultJson)) {
      throw new RuntimeException("occur a exception because return not json.");
    }

    DefaultESignResponse defaultESignResponse = JSONUtil
        .toBean(resultJson, DefaultESignResponse.class);

    String data = defaultESignResponse.getData();
    Class<T> responseClass = request.getResponseClass();
    T t = JSONUtil.toBean(data, responseClass);

    t.setCode(defaultESignResponse.getCode());
    t.setMessage(defaultESignResponse.getMessage());
    return t;
  }

}
